﻿//JumbotCms_4.1 Final
using System;
using System.Data;
using System.Web;
using Jumbot.Common;
using JumbotCms.Common;
namespace JumbotCms.Modules.Article.CollectItem
{
    public partial class _ajax : JumbotCms.API.AdminCenter
    {
        private string _operType = string.Empty;
        private string _response = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            ChannelId = Str2Str(q("ccid"));
            id = Str2Str(q("id"));
            Admin_Load("", "json", true);
            this._operType = q("oper");
            switch (this._operType)
            {
                case "ajaxGetList":
                    ajaxGetList();
                    break;
                case "ajaxBatchOper":
                    ajaxBatchOper();
                    break;
                case "ajaxCopy":
                    ajaxCopy();
                    break;
                case "ajaxColl":
                    ajaxColl();
                    break;
                case "ajaxInput":
                    ajaxInput();
                    break;
                case "checkname":
                    ajaxCheckName();
                    break;
                default:
                    DefaultResponse();
                    break;
            }
            Response.Write(this._response);
        }

        private void DefaultResponse()
        {
            this._response = JsonResult(0, "未知操作");
        }
        private void ajaxCheckName()
        {
            if (id == "0")
            {
                doh.Reset();
                doh.ConditionExpress = "title=@title and channelid=" + ChannelId;
                doh.AddConditionParameter("@title", q("txtTitle"));
                if (doh.Exist("jcms_module_article_collitem"))
                    this._response = JsonResult(0, "不可添加");
                else
                    this._response = JsonResult(1, "可以添加");
            }
            else
            {
                doh.Reset();
                doh.ConditionExpress = "title=@title and id<>" + q("id") + " and channelid=" + ChannelId;
                doh.AddConditionParameter("@title", q("txtTitle"));
                if (doh.Exist("jcms_module_article_collitem"))
                    this._response = JsonResult(0, "不可修改");
                else
                    this._response = JsonResult(1, "可以修改");
            }
        }
        private void ajaxGetList()
        {
            //具备内容录入的管理员才可以进来
            Admin_Load(ChannelId + "-01", "json");
            int page = Int_ThisPage();
            int PSize = Str2Int(q("pagesize"), 20);
            int countNum = 0;
            string sqlStr = "SELECT a.id as id,a.Title as ItemName,webname,ClassId,b.Title as ClassName,flag FROM [jcms_module_article_collitem] a LEFT JOIN [jcms_normal_class] b on a.classid=b.id WHERE a.channelid=" + ChannelId;
            doh.Reset();
            doh.SqlCmd = sqlStr;
            DataTable dt = doh.GetDataTable();
            countNum = dt.Rows.Count;
            this._response = "{result :\"1\"," +
                "returnval :\"操作成功\"," +
                "pagerbar :\"" + Jumbot.Common.HtmlPager.GetPageBar(3, "js", 2, countNum, PSize, page, "javascript:ajaxList(<#page#>);") + "\"," +
                Jumbot.Common.JsonHelp.DtToSON(dt) +
                "}";
            dt.Clear();
            dt.Dispose();
        }
        private void ajaxCopy()
        {
            Admin_Load("0000", "json");
            string lId = f("id");
            doh.Reset();
            doh.SqlCmd = "SELECT * FROM [jcms_module_article_collitem] WHERE [Id]=" + lId + " and channelid=" + ChannelId;
            DataTable dtCollItem = doh.GetDataTable();
            if (dtCollItem.Rows.Count > 0)
            {
                doh.Reset();
                for (int i = 0; i < dtCollItem.Columns.Count; i++)
                {
                    if (dtCollItem.Columns[i].ColumnName.ToLower() != "id")
                    {
                        doh.AddFieldItem(dtCollItem.Columns[i].ColumnName, dtCollItem.Rows[0][i].ToString());
                    }
                }
                doh.Insert("jcms_module_article_collitem");
            }
            dtCollItem.Clear();
            dtCollItem.Dispose();
            this._response = JsonResult(1, "成功克隆");
        }
        private void ajaxInput()
        {
            Admin_Load("0000", "json");
            string XmlPath = Server.MapPath(f("txtXmlPath"));
            if (!System.IO.File.Exists(XmlPath))
            {
                this._response = JsonResult(0, "项目Xml不存在");
                return;
            }
            DataSet ds = Jumbot.Common.XmlCOM.ReadXml(Server.MapPath(f("txtXmlPath")));
            int succeedNum = 0;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                doh.Reset();
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    if (ds.Tables[0].Columns[i].ColumnName.ToLower() != "id")
                        doh.AddFieldItem(ds.Tables[0].Columns[i].ColumnName.ToString(), dr[i].ToString());
                }
                doh.Insert("jcms_module_article_collitem");
                succeedNum++;
            }
            this._response = JsonResult(1, succeedNum + "条采集项目导入成功");
        }
        /// <summary>
        /// 执行批量操作
        /// </summary>
        /// <param name="oper"></param>
        /// <param name="ids"></param>
        private void ajaxBatchOper()
        {
            Admin_Load(ChannelId + "-01", "json");
            string act = q("act");
            string ids = f("ids");
            string[] idValue;
            idValue = ids.Split(',');
            if (act == "del")
            {
                for (int i = 0; i < idValue.Length; i++)
                {
                    doh.Reset();
                    doh.ConditionExpress = "[ItemId]=" + idValue[i];
                    if (doh.Exist("jcms_module_article_collfilters"))
                        continue;
                    else
                    {
                        doh.Reset();
                        doh.ConditionExpress = "[ItemId]=" + idValue[i];
                        doh.Delete("jcms_module_article_collhistory");
                        doh.Reset();
                        doh.ConditionExpress = "id=" + idValue[i];
                        doh.Delete("jcms_module_article_collitem");
                    }
                }
                this._response = JsonResult(1, "删除成功");
            }
            else if (act == "out")
            {
                doh.Reset();
                doh.SqlCmd = "SELECT Id,Title,ChannelId,ClassId,WebName,WebUrl,ItemDemo,ListStr,LsString,LoString,HsString,HoString,TsString,ToString,CsString,CoString,NPsString,NPoString,AuthorStr,SourceFrom,Flag,Script_Iframe,Script_Object,Script_Script,Script_Div,Script_Table,Script_Span,Script_Img,Script_Font,Script_A,Script_Html,CollecNewsNum,SaveFiles,CollecOrder,ListWebEncode,ContentWebEncode" +
                    " FROM [jcms_module_article_collitem] WHERE [Id] in (" + ids + ")";
                DataTable dt = doh.GetDataTable();
                dt.WriteXml(Server.MapPath("~/_data/databackup/collitem" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xml"), XmlWriteMode.IgnoreSchema);
                this._response = JsonResult(1, "导出成功");
            }
            else
                this._response = JsonResult(0, "执行错误");
        }
        private void ajaxColl()
        {
            Admin_Load(ChannelId + "-01", "json");
            string id = f("id");
            if (id == "0")
            {
                this._response = JsonResult(0, "参数错误，项目ID不能为 0");
                return;
            }
            doh.Reset();
            doh.SqlCmd = "SELECT * FROM [jcms_module_article_collitem] WHERE [Id]=" + id;
            DataTable dtCollItem = doh.GetDataTable();
            if (dtCollItem.Rows.Count == 0)
            {
                this._response = JsonResult(0, "ID为 " + id + " 的项目不存在");
                return;
            }
            int CollecNewsNum = Str2Int(dtCollItem.Rows[0]["CollecNewsNum"].ToString());

            string ClId = dtCollItem.Rows[0]["ClassId"].ToString();
            string AddDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string Author = dtCollItem.Rows[0]["AuthorStr"].ToString();
            string SourceFrom = dtCollItem.Rows[0]["SourceFrom"].ToString();

            string ListStr = dtCollItem.Rows[0]["ListStr"].ToString();
            string LsString = dtCollItem.Rows[0]["LsString"].ToString();
            string LoString = dtCollItem.Rows[0]["LoString"].ToString();
            string HsString = dtCollItem.Rows[0]["HsString"].ToString();
            string HoString = dtCollItem.Rows[0]["HoString"].ToString();
            string CollecOrder = dtCollItem.Rows[0]["CollecOrder"].ToString();
            string ListWebEncode = dtCollItem.Rows[0]["ListWebEncode"].ToString();
            string ContentWebEncode = dtCollItem.Rows[0]["ContentWebEncode"].ToString();
            string TsString = dtCollItem.Rows[0]["TsString"].ToString();
            string ToString = dtCollItem.Rows[0]["ToString"].ToString();
            string CsString = dtCollItem.Rows[0]["CsString"].ToString();
            string CoString = dtCollItem.Rows[0]["CoString"].ToString();
            string NPsString = dtCollItem.Rows[0]["NPsString"].ToString();
            string NPoString = dtCollItem.Rows[0]["NPoString"].ToString();
            string SaveFiles = dtCollItem.Rows[0]["SaveFiles"].ToString();
            string Script_Iframe = dtCollItem.Rows[0]["Script_Iframe"].ToString();
            string Script_Object = dtCollItem.Rows[0]["Script_Object"].ToString();
            string Script_Script = dtCollItem.Rows[0]["Script_Script"].ToString();
            string Script_Div = dtCollItem.Rows[0]["Script_Div"].ToString();
            string Script_Table = dtCollItem.Rows[0]["Script_Table"].ToString();
            string Script_Span = dtCollItem.Rows[0]["Script_Span"].ToString();
            string Script_Img = dtCollItem.Rows[0]["Script_Img"].ToString();
            string Script_Font = dtCollItem.Rows[0]["Script_Font"].ToString();
            string Script_A = dtCollItem.Rows[0]["Script_A"].ToString();
            string Script_Html = dtCollItem.Rows[0]["Script_Html"].ToString();
            dtCollItem.Clear();
            dtCollItem.Dispose();
            System.Text.Encoding LencodeType = System.Text.Encoding.Default;
            System.Text.Encoding CencodeType = System.Text.Encoding.Default;
            switch (ListWebEncode)
            {
                case "3":
                    LencodeType = System.Text.Encoding.Unicode;
                    break;
                case "2":
                    LencodeType = System.Text.Encoding.UTF8;
                    break;
                case "1":
                    LencodeType = System.Text.Encoding.GetEncoding("GB2312");
                    break;
            }
            switch (ContentWebEncode)
            {
                case "3":
                    CencodeType = System.Text.Encoding.Unicode;
                    break;
                case "2":
                    CencodeType = System.Text.Encoding.UTF8;
                    break;
                case "1":
                    CencodeType = System.Text.Encoding.GetEncoding("GB2312");
                    break;
            }
            NewsCollection nc = new NewsCollection();
            string testList = nc.GetHttpPage(ListStr, 10000, LencodeType);
            if (testList == "$UrlIsFalse$")
            {
                this._response = JsonResult(0, "列表地址设置错误");
                return;
            }
            if (testList == "$GetFalse$")
            {
                this._response = JsonResult(0, "无法连接列表页或连接超时");
                return;
            }
            testList = nc.GetBody(testList, LsString, LoString, false, false);
            if (testList == "$StartFalse$")
            {
                this._response = JsonResult(0, "列表开始前标记设置错误,请重新设置");
                return;
            }
            if (testList == "$EndFalse$")
            {
                this._response = JsonResult(0, "列表结束后标记设置错误,请重新设置");
                return;
            }
            System.Collections.ArrayList linkArray = nc.GetArray(testList, HsString, HoString);
            if (linkArray.Count == 0)
            {
                this._response = JsonResult(0, "未取到链接,请检查链接设置");
                return;
            }
            if (linkArray[0].ToString() == "$StartFalse$")
            {
                this._response = JsonResult(0, "链接开始前标记设置错误,请重新设置");
                return;
            }
            if (linkArray[0].ToString() == "$EndFalse$")
            {
                this._response = JsonResult(0, "链接开始前标记设置错误,请重新设置");
                return;
            }
            if (linkArray[0].ToString() == "$NoneLink$")
            {
                this._response = JsonResult(0, "未取到链接,请检查链接设置");
                return;
            }
            if (CollecOrder == "1")
                linkArray.Reverse();
            if (CollecNewsNum > 0 && linkArray.Count > CollecNewsNum)
                linkArray.RemoveRange(CollecNewsNum, linkArray.Count - CollecNewsNum);
            string linkStr = string.Empty;

            int falseNum = 0;
            int successNum = 0;
            for (int i = 0; i < linkArray.Count; i++)
            {
                int IsImg = 0;
                string imgUrl = string.Empty;
                string photoUrl = string.Empty;
                linkStr = nc.DefiniteUrl(linkArray[i].ToString(), ListStr);
                if (linkStr == "$False$")
                {
                    falseNum++;
                    continue;
                }
                string newsCode = nc.GetHttpPage(linkStr, 8000, CencodeType);
                if (newsCode == "$UrlIsFalse$" || newsCode == "$GetFalse$")
                {
                    falseNum++;
                    continue;
                }
                string cTitle = nc.GetBody(newsCode, TsString, ToString, false, false);
                string cBody = nc.GetBody(newsCode, CsString, CoString, false, false);
                if (cTitle == "$StartFalse$" || cTitle == "$EndFalse$")
                {
                    falseNum++;
                    continue;
                }
                if (cBody == "$StartFalse$" || cBody == "$EndFalse$")
                {
                    falseNum++;
                    doh.Reset();
                    doh.AddFieldItem("ChannelId", ChannelId);
                    doh.AddFieldItem("ItemId", id);
                    doh.AddFieldItem("Title", cTitle);
                    doh.AddFieldItem("CollectDate", DateTime.Now.ToString());
                    doh.AddFieldItem("NewsUrl", linkStr);
                    doh.AddFieldItem("ResultStr", "在分析新闻正文时发生错误");
                    doh.AddFieldItem("Result", 0);
                    doh.Insert("jcms_module_article_collhistory");
                    continue;
                }
                string NewsPaingNext = nc.GetPaing(newsCode, NPsString, NPoString);//判断是否有下页
                int pageCount = 0;
                while (NewsPaingNext != "$StartFalse$" && NewsPaingNext != "$EndFalse$" && NewsPaingNext.Length > 0 && pageCount < 20)
                {

                    string NewsPaingNextCode = string.Empty;
                    string ContentTemp = string.Empty;
                    NewsPaingNext = nc.DefiniteUrl(NewsPaingNext, linkStr);
                    NewsPaingNextCode = nc.GetHttpPage(NewsPaingNext, 10000, CencodeType);
                    ContentTemp = nc.GetBody(NewsPaingNextCode, CsString, CoString, false, false);
                    if (ContentTemp == "$StartFalse$" || ContentTemp == "$EndFalse$")
                    {
                        break;//跳出循环
                    }
                    else
                    {
                        cBody = cBody + "<br>[Jumbot_PageBreak]<br>" + ContentTemp;
                        NewsPaingNext = nc.GetPaing(NewsPaingNextCode, NPsString, NPoString);
                    }
                    pageCount++;
                }

                System.Collections.ArrayList bodyArray = nc.ReplaceSaveRemoteFile(cBody, Request.PhysicalApplicationPath + "\\" + ChannelDir, site.Dir + ChannelDir, linkStr, SaveFiles);
                if (bodyArray.Count == 3)
                {
                    IsImg = 1;
                    imgUrl = bodyArray[1].ToString();
                    photoUrl = bodyArray[2].ToString();
                }
                cBody = bodyArray[0].ToString();
                NewsCollFilter nf = new NewsCollFilter();
                cBody = nf.FilterBody(doh, cBody, id, "Body");//采用项目过滤内容
                //过滤开始
                if (Script_Iframe == "1")
                    cBody = nc.ScriptHtml(cBody, "Iframe", 1);
                if (Script_Object == "1")
                    cBody = nc.ScriptHtml(cBody, "Object", 2);
                if (Script_Script == "1")
                    cBody = nc.ScriptHtml(cBody, "Script", 2);
                if (Script_Div == "1")
                    cBody = nc.ScriptHtml(cBody, "Div", 3);
                if (Script_Table == "1")
                    cBody = nc.ScriptHtml(cBody, "Table", 2);
                if (Script_Span == "1")
                    cBody = nc.ScriptHtml(cBody, "Span", 3);
                if (Script_Img == "1")
                    cBody = nc.ScriptHtml(cBody, "Img", 3);
                if (Script_Font == "1")
                    cBody = nc.ScriptHtml(cBody, "Font", 3);
                if (Script_A == "1")
                    cBody = nc.ScriptHtml(cBody, "A", 3);
                if (Script_Html == "1")
                    cBody = nc.DelHtml(cBody);
                //过滤结束
                //判断重复性
                doh.Reset();
                doh.ConditionExpress = "title=@title and channelid=" + ChannelId;
                doh.AddConditionParameter("@title", cTitle);
                if (doh.Exist("jcms_module_article_collhistory"))
                {
                    falseNum++;
                }
                else
                {
                    doh.Reset();
                    doh.ConditionExpress = "title=@title and channelid=" + ChannelId;
                    doh.AddConditionParameter("@title", cTitle);
                    if (doh.Exist("jcms_module_article"))
                    {
                        falseNum++;
                    }
                    else
                    {
                        doh.Reset();
                        doh.AddFieldItem("Title", nf.FilterBody(doh, cTitle, id, "Title"));
                        doh.AddFieldItem("TColor", "");
                        doh.AddFieldItem("ChannelId", ChannelId);
                        doh.AddFieldItem("ClassId", ClId);
                        doh.AddFieldItem("AddDate", AddDate);
                        doh.AddFieldItem("Content", cBody);
                        doh.AddFieldItem("ViewNum", 0);

                        doh.AddFieldItem("Author", Author);
                        doh.AddFieldItem("Editor", AdminName);
                        doh.AddFieldItem("UserId", 0);
                        doh.AddFieldItem("IsPass", 0);
                        doh.AddFieldItem("IsImg", IsImg);
                        doh.AddFieldItem("Img", imgUrl);
                        doh.AddFieldItem("IsTop", 0);
                        doh.AddFieldItem("SourceFrom", SourceFrom);
                        doh.AddFieldItem("Summary", GetCutString(Jumbot.Common.Strings.NoHTML(cBody), 200));
                        doh.Insert("jcms_module_article");

                        successNum++;
                        doh.Reset();
                        doh.AddFieldItem("ChannelId", ChannelId);
                        doh.AddFieldItem("ItemId", id);
                        doh.AddFieldItem("Title", cTitle);
                        doh.AddFieldItem("CollectDate", DateTime.Now.ToString());
                        doh.AddFieldItem("NewsUrl", linkStr);
                        doh.AddFieldItem("ResultStr", "采集成功");
                        doh.AddFieldItem("Result", 1);
                        doh.Insert("jcms_module_article_collhistory");
                    }
                }
                this._response = JsonResult(0, "采集完成,成功 " + successNum + " ,失败 " + falseNum);
                if (this._response.Length == 0)
                    this._response = JsonResult(0, "未知错误!");
            }
        }
    }
}